<template>
  <el-dialog v-model="dialogVisible" title="导出停机时间数据" width="800px" :close-on-click-modal="false" @close="handleClose">
    <div class="export-dialog">
      <!-- 分厂选择按钮 -->
      <div class="factory-buttons">
        <div class="section-title">选择分厂：</div>
        <el-radio-group v-model="selectedFactory" @change="handleFactoryChange">
          <el-radio-button :value="1">一分厂</el-radio-button>
          <el-radio-button :value="2">二分厂</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 穿梭框 -->
      <div class="transfer-container">
        <div class="section-title">选择产线：</div>
        <el-transfer
          v-model="selectedLines"
          :data="transferData"
          :titles="['可选产线', '已选产线']"
          :props="{ key: 'id', label: 'name' }"
          filterable
          filter-placeholder="请输入产线名称"
        />
      </div>

      <!-- 时间范围选择 -->
      <div class="time-range-container">
        <div class="section-title">时间范围：</div>
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled-date="disabledDate"
          style="width: 100%"
        />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleExport" :loading="exportLoading">导出</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from "vue"
import { ElMessage } from "element-plus"
import { organTree } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
import { useUserStore } from "@/stores/modules/user"
import dayjs from "dayjs"

// Props
interface Props {
  modelValue: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
})

// Emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void
}>()

// 数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val)
})

const selectedFactory = ref<1 | 2>(1) // 选择的分厂：1-一分厂，2-二分厂
const selectedLines = ref<number[]>([]) // 选中的产线ID
const timeRange = ref<[string, string] | null>(null) // 时间范围
const exportLoading = ref(false) // 导出加载状态

// 原始数据
const factoryList = ref<SystemApi.OrganTree[]>([]) // 分厂列表
const allLineList = ref<SystemApi.OrganTree[]>([]) // 所有产线列表

// 穿梭框数据 - 根据选择的分厂过滤产线
const transferData = computed(() => {
  console.log("factoryList", factoryList.value)
  console.log("selectedFactory", selectedFactory.value)

  // 根据分厂名称或索引查找对应的分厂
  let factory = null

  if (factoryList.value.length > 0) {
    // 方法1: 根据名称匹配（更可靠）
    const factoryName = selectedFactory.value === 1 ? "一分厂" : "二分厂"
    factory = factoryList.value.find(f => f.organName.includes(factoryName))

    // 方法2: 如果根据名称找不到，使用索引
    if (!factory && factoryList.value.length >= selectedFactory.value) {
      factory = factoryList.value[selectedFactory.value - 1]
    }
  }

  console.log("selected factory", factory)

  if (!factory || !factory.childrenTree || factory.childrenTree.length === 0) {
    console.log("没有找到分厂或产线数据")
    return []
  }

  const lines = factory.childrenTree.map(line => ({
    id: line.id,
    name: line.organName
  }))

  console.log("transferData lines", lines)
  return lines
})

// 禁用今天之后的日期
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 方法
// 获取分厂和产线数据
const getFactoryAndLineData = async () => {
  try {
    const { data } = await organTree()
    console.log("organTree raw data", data)

    if (data && data.length > 0) {
      // 数据结构：根节点(level=0) -> childrenTree包含分厂(level=1) -> childrenTree包含产线(level=2)
      const rootNode = data[0]

      if (rootNode && rootNode.childrenTree) {
        // 过滤出level为1的分厂数据
        factoryList.value = rootNode.childrenTree.filter(item => item.level === 1)
        console.log("factoryList after filter", factoryList.value)

        // 提取所有产线数据
        allLineList.value = factoryList.value.flatMap(factory => factory.childrenTree || [])
        console.log("allLineList", allLineList.value)
      }
    }
  } catch (error) {
    console.error("获取分厂和产线数据失败", error)
    ElMessage.error("获取分厂和产线数据失败")
  }
}
// 处理分厂切换
const handleFactoryChange = () => {
  // 切换分厂时清空已选产线
  selectedLines.value = []
}

// 监听对话框打开
watch(
  () => props.modelValue,
  val => {
    if (val) {
      // 初始化数据
      selectedFactory.value = 1
      selectedLines.value = []
      timeRange.value = null

      // 加载数据
      getFactoryAndLineData()
    }
  }
)

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 导出数据
const handleExport = async () => {
  // 验证
  if (selectedLines.value.length === 0) {
    ElMessage.warning("请至少选择一条产线")
    return
  }

  if (!timeRange.value || timeRange.value.length !== 2) {
    ElMessage.warning("请选择时间范围")
    return
  }

  try {
    exportLoading.value = true

    // 构建参数 - 对接 device/stop/export 接口
    const queryParams = {
      lineIds: selectedLines.value.join(","), // 将产线ID数组转换为逗号分隔的字符串
      startTime: timeRange.value[0], // 开始时间
      endTime: timeRange.value[1] // 结束时间
    }

    // 使用原生fetch完全绕过axios拦截器
    const baseURL = import.meta.env.VITE_API_URL
    const userStore = useUserStore()

    // 构建完整URL
    const queryString = Object.keys(queryParams)
      .filter(key => {
        const value = queryParams[key as keyof typeof queryParams]
        return value !== undefined && value !== null && value !== ""
      })
      .map(key => {
        const value = queryParams[key as keyof typeof queryParams]
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
      })
      .join("&")

    const fullUrl = `${baseURL}/device/stop/export?${queryString}`
    console.log("导出URL：", fullUrl)

    const response = await fetch(fullUrl, {
      method: "GET",
      headers: {
        token: userStore.token
      }
    })

    console.log("fetch响应：", response)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const content = await response.blob()
    console.log("blob内容：", content)

    // 创建带正确MIME类型的Blob，解决乱码问题
    const blob = new Blob([content], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    })
    const factoryName = selectedFactory.value === 1 ? "一分厂" : "二分厂"
    const fileName = `停机数据_${factoryName}_${dayjs().format("YYYY-MM-DD_HHmmss")}.xlsx`

    if ("download" in document.createElement("a")) {
      // 非IE下载
      const elink = document.createElement("a")
      elink.download = fileName
      elink.style.display = "none"
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      ;(navigator as any).msSaveBlob(blob, fileName)
    }

    ElMessage.success("导出成功")
    handleClose()
  } catch (error) {
    console.error("导出失败：", error)
    ElMessage.error("导出失败，请重试")
  } finally {
    exportLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.export-dialog {
  .section-title {
    margin-bottom: 12px;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
  }

  .factory-buttons {
    margin-bottom: 24px;

    :deep(.el-radio-group) {
      display: flex;
      gap: 12px;
    }

    :deep(.el-radio-button) {
      flex: 1;
    }

    :deep(.el-radio-button__inner) {
      width: 100%;
      text-align: center;
      border: 1px solid var(--el-border-color);
    }
  }

  .transfer-container {
    margin-bottom: 24px;

    :deep(.el-transfer) {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    :deep(.el-transfer-panel) {
      width: 45%;
    }

    :deep(.el-transfer__buttons) {
      padding: 0 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 10px;
    }

    :deep(.el-transfer__button) {
      display: block;
      margin: 0;
    }
  }

  .time-range-container {
    :deep(.el-date-editor) {
      width: 100%;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
